package cn.lu.joke.util;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Locale;
import java.util.regex.Pattern;

/**
 * Created by luxianyue on 2018/3/22.
 */

public class NumberUtils {

    private static Pattern mPattern;

    public static boolean isNumber(String str) {
        if (str != null) {
            if (mPattern == null) {
                mPattern = Pattern.compile("[\\d]+[.]?[\\d]*");
            }
            return mPattern.matcher(str).matches();
        }
        return false;
    }

    /** 不适用科学计数法
     * 直接截断 spot位小数点，不进行四舍五入
     * @param number
     * @param spot
     * @return
     */
    public static double getFormatDoubleNum(double number, int spot) {
        String num = Double.toString(number);
        int index = num.indexOf(".");
        if (num.contains(".") && num.substring(index).length() > spot + 1) {
            return Double.parseDouble(num.substring(0, index + spot + 1));
        }
        return number;
    }

    /**
     * 保留 spot位小数点，不进行四舍五入
     * @param number
     * @return
     */
    public static String getFormatNum2(double number, int spot) {
        StringBuilder strPot = new StringBuilder(".");
        for (int i = 0; i < spot; i++) {
            strPot.append("#");
        }
        DecimalFormat df = new DecimalFormat("#" + strPot);
        df.setRoundingMode(RoundingMode.FLOOR);
        return df.format(number);
    }

    public static String getFormatCount(long count) {
        if (count < 10000) {
            return Long.toString(count);
        }
        float fcount = count * 1f / 10000;
        String strCount = String.format(Locale.getDefault(), "%.2f", fcount);
        int index = strCount.indexOf(".");
        if (Integer.parseInt(strCount.substring(index + 1)) == 0) {
            strCount = strCount.substring(0, index);
        }
        return strCount + "万";
    }
}
